/**
 * @Author: lifuzhao
 * @Date: 2019-08-06
 * @Project: shop_cms
 */
import axios, { CancelToken } from 'axios';
import store from '../vuex/index';
import router from '../router/index';
// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || ''
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

let config = {
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
};

const $axios = axios.create(config);
const ajaxMap = {};
$axios.interceptors.request.use(
  (_config) => {
    const { url } = _config;
    if (url !== '/api/v1/token/admin') {
      config.headers.token = store.state.token;
    }
    if (config.abort && ajaxMap[url]) {
      ajaxMap[url]();
    }
    // eslint-disable-next-line no-return-assign
    config.cancelToken = new CancelToken(excutor => ajaxMap[url] = excutor);
    // Do something before request is sent
    return config;
  },
  (error) => {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axios.interceptors.response.use(
  function (response) {
    // Do something with response data
    let { config, data } = response;
    if (data.errorCode) {
      data.success = false;
      data.msg = data.msg ? '，失败原因：' + data.msg : '';
      if (data.errorCode === 10001) {
        router.push({
          path: '/login'
        });
      }
    } else {
      data = data.data || {};
      data.success = true;
    }
    delete _ajaxMap[config.url];
    return data;
  },
  function (error) {
    // Do something with response error
    return Promise.reject(error);
  }
);

_axios.install = function (Vue) {
  Vue.prototype.$axios = Vue.prototype.axios = _axios;
};
export default _axios;
